package com.sanchunhui.psc.ui.activity

import android.app.AlertDialog
import android.bluetooth.*
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Point
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.listener.OnItemLongClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.eightbitlab.rxbus.Bus
import com.noober.menu.FloatMenu
import com.sanchunhui.psc.R
import com.sanchunhui.psc.bluetooth.ble.BleBlueImpl
import com.sanchunhui.psc.bluetooth.ble.BleBlueImpl.handler
import com.sanchunhui.psc.bluetooth.ble.BleData
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.data.protocol.Member
import com.sanchunhui.psc.data.protocol.ResponseInfo
import com.sanchunhui.psc.event.DeviceInfoReadEvent
import com.sanchunhui.psc.event.DeviceMessagePublishEvent
import com.sanchunhui.psc.event.KaiGongHexEvent
import com.sanchunhui.psc.injection.component.DaggerDeviceComponent
import com.sanchunhui.psc.injection.module.DeviceModule
import com.sanchunhui.psc.presenter.AddDevicePresenter
import com.sanchunhui.psc.presenter.view.DeviceView
import com.sanchunhui.psc.ui.adapter.BaseRecyclerViewAdapter
import com.sanchunhui.psc.ui.adapter.DeviceListAdapter
import com.sanchunhui.psc.utils.HexUtil
import com.sanchunhui.psc.utils.bleuitls.callback.ConnectCallback
import com.sanchunhui.psc.utils.bleuitls.callback.OnReceiverCallback
import com.sanchunhui.psc.utils.bleuitls.request.ReceiverRequestQueue
import com.sanchunhui.psc.widgets.BatteryView
import com.sanchunhui.ui.activity.BaseMvpActivity
import kotlinx.android.synthetic.main.activity_add_team.*
import kotlinx.android.synthetic.main.activity_device_list.*
import kotlinx.android.synthetic.main.header.*
import org.jetbrains.anko.startActivity
import java.util.*

/**
 * @Author zyx
 * @Date 2021/6/24-8:57
 * @Dscribe
 */
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class DeviceListActivity : BaseMvpActivity<AddDevicePresenter>(), DeviceView {

    private val TAG = "DeviceListActivity"

    private var blueBeans: MutableList<BluetoothDevice> = mutableListOf()
    private val mData: MutableList<BleData> = mutableListOf()
    private lateinit var mBleAdapter: DeviceListAdapter
    private var bluetoothAdapter: BluetoothAdapter? = null
    private var blueGatt: BluetoothGatt? = null
    private var mBluetoothGatt: BluetoothGatt? = null
    private lateinit var mInfoTv: TextView
    private var isConnected = false
    private var connectedPosition : Int = -1
    private var floatMenuPosition : Int = -1

    //获取到所有服务的集合
    private val servicesMap = HashMap<String, Map<String, BluetoothGattCharacteristic>>()
    //读操作请求队列
    private val mReceiverRequestQueue = ReceiverRequestQueue()

    private val mHandler = Handler(Looper.getMainLooper())

    //连接结果的回调
    private var connectCallback: ConnectCallback? = null

    private var mBleGattCharacteristic: BluetoothGattCharacteristic? = null

    /**
     * UI
     */
    private var itemStateTv: TextView? = null
    private var powerNumberTv : TextView? = null
    private var deviceNameTv : TextView?= null
    private lateinit var horizontalBattery : BatteryView
    private var power : Int = 0 // 电量
    private var lastPower : Int = 0 // 上次电量

    // 触摸中心点
    private val point = Point()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_device_list)
        initHeader()
        initView()
        //是否支持低功耗蓝牙
        initBluetooth()
        initObserve()

        // 获取已绑定的设备
        BleBlueImpl.foundDevices {dev ->
            val bean = BleData(0,dev, "")
            bean.dev.name?.let {
                if (bean !in mData) {
                    mData.add(bean)
                }
            }
            mBleAdapter.setData(mData)
        }
    }

    override fun onStart() {
        super.onStart()
        // 扫描设备
//        scan(contentView)
    }

    private fun initHeader() {
        back.visibility = View.VISIBLE
        headerTitle.visibility = View.VISIBLE
        headerTitle.text = "设备管理"
        back.setOnClickListener { finish() }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            1 -> {
//                teamLeaderName = data!!.getStringExtra("teamLeaderName")
//                leaderMemberId = data.getStringExtra("leaderMemberId")
////              et_team_leader.text =  Editable.Factory.getInstance().newEditable(teamLeaderName)
//                et_team_leader.text =  teamLeaderName
            }
        }
    }

    /*
        Dagger注册
    */
    override fun injectComponent() {
        DaggerDeviceComponent.builder().activityComponent(mActivityComponent).deviceModule(
                DeviceModule()).build().inject(this)
        mPresenter.mView = this
    }

    /*
        添加设备记录回调结果
     */
    override fun onMemberAddDeviceResult(result: ResponseInfo) {
        if (result.code == 0) {
//            val toast = Toast.makeText(this, "添加设备成功", Toast.LENGTH_SHORT)
//            toast.setGravity(Gravity.CENTER, 0, 0)
//            toast.show()
        } else if (result.code == 401) {
            startActivity<LoginActivity>()
        } else {
            val toast = Toast.makeText(this, result.message, Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }
    }

    // 注册观察者
    private fun initObserve() {

    }

    /**
       初始化 view
     */
    private fun initView() {
//        val recyclerView: RecyclerView = findViewById(R.id.recycler_device_list)
//        val manager = LinearLayoutManager(this)
        recycler_device_list.layoutManager = LinearLayoutManager(this)
//        recyclerView.layoutManager = manager
        mBleAdapter = DeviceListAdapter(this)
        recycler_device_list.adapter = mBleAdapter

        // 适配器点击条目
        mBleAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<BleData> {
            override fun onItemClick(item: BleData, position: Int) {
                //连接之前先关闭连接
//                closeConnect()
//                val bleData = mData[position]
//                itemStateTv = findViewById(R.id.blue_device_item_status_tv)
//                blueGatt = bleData.dev.connectGatt(this@DeviceListActivity, false, blueGattListener)
//                Toast.makeText(this@DeviceListActivity, "开始与 ${bleData.dev.name} 连接....", Toast.LENGTH_SHORT).show()
            }
        })

        // 适配器长按条目
        mBleAdapter.setOnItemLongClickListener(object :BaseRecyclerViewAdapter.OnItemLongClickLintener<BleData>{
            override fun onItemLongClick(item: BleData, position: Int) {
                connectedPosition = position
                val bleData = mData[position]
                val floatMenu = FloatMenu(this@DeviceListActivity)
                floatMenu.items("连接","断开","绑定","解绑","删除","开工","设备名称")
                floatMenu.setOnItemClickListener { v, position ->
                    val user = BaseApplication.mUser
                    if (position == 0) {
                        //连接之前先关闭连接
                        closeConnect()
//                        deviceNameTv = findViewById(R.id.blue_item_name_tv)
//                        itemStateTv = findViewById(R.id.blue_device_item_status_tv)
//                        horizontalBattery =  findViewById(R.id.horizontalBattery)
//                        powerNumberTv = findViewById(R.id.tv_power_number)
                        blueGatt = bleData.dev.connectGatt(this@DeviceListActivity, false, blueGattListener)
                        val toast = Toast.makeText(this@DeviceListActivity, "请稍后，开始与 ${bleData.dev.name} 连接....", Toast.LENGTH_SHORT)
                        toast.setGravity(Gravity.CENTER, 0, 0)
                        toast.show()
                    } else if (position == 1) {
                        closeConnect()
                    } else if (position == 2) {
                        mPresenter.addDeviceForMember(user.token.toString(), bleData.dev.address,bleData.dev.type,bleData.dev.name)
                    } else if (position == 3) {

                    } else if (position == 4) {

                    } else if (position == 5) {
                        openWork()
                    } else if (position == 6) {
                        floatMenuPosition = 6
                        var editText = EditText(this@DeviceListActivity)
                        editText.text = Editable.Factory.getInstance().newEditable(item.dev.name.toString())
                        AlertDialog.Builder(this@DeviceListActivity)
                            .setTitle("设置名称")
                            .setView(editText)
                            .setNegativeButton(R.string.cancel, null)
                            .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener {
                                    dialogInterface, i ->
                                var inputName = editText.getText().toString()
                                setDeviceName(inputName)
                            })
                            .show()
                    }
                }
                floatMenu.show(point)
            }
        })
    }

    /*
        设置设备名称
     */
    fun setDeviceName(value:String) {
        if (value.length > 10) {
            val toast = Toast.makeText(this, "设备名不能超过10字符", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
            return
        }
        if (mBleGattCharacteristic == null) {
            mBleGattCharacteristic =
                getBluetoothGattCharacteristic(BleBlueImpl.UUID_SERVICE.toString(), BleBlueImpl.UUID_WRITE.toString())
        }
        if (null == mBleGattCharacteristic) {
            Toast.makeText(this, "fail", Toast.LENGTH_SHORT).show()
        }
        //设置数组进去
        mBleGattCharacteristic!!.setValue(HexUtil.deviceNameToBytes(value))
        //发送
        val b = blueGatt!!.writeCharacteristic(mBleGattCharacteristic)
        Log.e(TAG, "send:" + b + "data：" + value)
    }

    /*
        开工
     */
    fun openWork() {
        if (mBleGattCharacteristic == null) {
            mBleGattCharacteristic =
                getBluetoothGattCharacteristic(BleBlueImpl.UUID_SERVICE.toString(), BleBlueImpl.UUID_WRITE.toString())
        }
        if (null == mBleGattCharacteristic) {
            Toast.makeText(this, "fail", Toast.LENGTH_SHORT).show()
        }
        //设置数组进去
        mBleGattCharacteristic!!.setValue(HexUtil.hexStringToBytes("68020d"))
        //发送
        val b = blueGatt!!.writeCharacteristic(mBleGattCharacteristic)
        Log.e(TAG, "send:" + b)
    }

    /*
        获取触摸的中心点
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.getAction() == MotionEvent.ACTION_DOWN) {
            point.x = ev.getRawX().toInt()
            point.y = ev.getRawY().toInt()
        }
        return super.dispatchTouchEvent(ev)
    }

    /*
       判断是否支持低功耗蓝牙
     */
    private fun initBluetooth() {
        packageManager.takeIf { !it.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) }
            ?.let {
                Toast.makeText(this, "您的设备没有低功耗蓝牙驱动！", Toast.LENGTH_SHORT).show()
                finish()
            }
    }

    /**
     * 设置读取数据的监听
     *
     * @param requestKey
     * @param onReceiverCallback
     */
    fun RegistReciveListener(requestKey: String, onReceiverCallback: OnReceiverCallback) {
        mReceiverRequestQueue[requestKey] = onReceiverCallback
    }

    /**
     * 扫描
     */
    fun scan(view: View) {
        mData.clear()
        mBleAdapter?.notifyDataSetChanged()
        BleBlueImpl.scanDev { dev ->
            dev.dev.name?.let {
                if (dev !in mData) {
                    mData.add(dev)
                }
            }
            mBleAdapter.setData(mData)
        }
    }

    /**
     * 编辑
     */
    @RequiresApi(Build.VERSION_CODES.N)
    fun edit(view: View) {
        val intent: Intent = Intent(this, DeviceInfoActivity::class.java)
        intent.putExtra("mBleGattCharacteristic", mBleGattCharacteristic)
        startActivityForResult(intent, 1)
    }

    // logInfo
    val sb  = StringBuilder()
    private fun logInfo(msg:String){
        runOnUiThread {
            sb.apply {
                append(msg).append("\n")
                mInfoTv.text = toString()
            }
        }
    }

    /**
     * 断开连接
     */
    private fun closeConnect() {
        BleBlueImpl.stopScan()
        blueGatt?.let {
            it.disconnect()
            it.close()
        }
    }

    /**
     * 蓝牙GATT连接及操作事件回调
     */
    private val blueGattListener = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
            super.onConnectionStateChange(gatt, status, newState)
            val device = gatt?.device
            if (newState == BluetoothProfile.STATE_CONNECTED) { // 连接成功
                isConnected = true
                //开始发现服务，有个小延时，最后200ms后尝试发现服务
                handler.postDelayed({
                    gatt?.discoverServices()
                    mBleAdapter.notifyDataSetChanged()
                }, 300)

                device?.let {
                    runOnUiThread {
                        val toast = Toast.makeText(this@DeviceListActivity, "与 ${it.name} 连接成功", Toast.LENGTH_SHORT)
                        toast.setGravity(Gravity.CENTER, 0, 0)
                        toast.show()
                        mBleAdapter.connectedPosition = connectedPosition
                        mBleAdapter.notifyItemChanged(connectedPosition)
                    }
                }

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // 断开连接
                connectedPosition = -1
                isConnected = false
                runOnUiThread {
                    val toast = Toast.makeText(this@DeviceListActivity, "无法与 ${device?.name} 连接: $status", Toast.LENGTH_SHORT)
                    toast.setGravity(Gravity.CENTER, 0, 0)
                    toast.show()
//                    Toast.makeText(this@DeviceListActivity, "无法与 ${device?.name} 连接: $status", Toast.LENGTH_SHORT).show()
                }
                closeConnect()
            }
        }

        // 发现新服务
        override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
            super.onServicesDiscovered(gatt, status)

            if (null != blueGatt && status == BluetoothGatt.GATT_SUCCESS) {
                val services : MutableList<BluetoothGattService>? = blueGatt!!.services
                for (i in services!!.indices) {
                    val charMap = HashMap<String, BluetoothGattCharacteristic>()
                    val bluetoothGattService = services[i]
                    val serviceUuid = bluetoothGattService.uuid.toString()
                    val characteristics = bluetoothGattService.characteristics
                    for (j in characteristics.indices) {
                        charMap.put(characteristics.get(j).uuid.toString(), characteristics.get(j))
                    }
                    servicesMap.put(serviceUuid, charMap)
                }
                val NotificationCharacteristic =
                    getBluetoothGattCharacteristic(BleBlueImpl.UUID_SERVICE.toString(), BleBlueImpl.UUID_READ_NOTIFY.toString())
                if (NotificationCharacteristic == null) {
                    return
                } else {
                    enableNotification(true, NotificationCharacteristic)
                }
            }

            /*
            if (status == BluetoothGatt.GATT_SUCCESS){
                gatt?.services?.forEach {service ->
                    Log.e("service 的 uuid:" ,"${service.uuid}")
                    service.characteristics.forEach{ characteristic ->
                        Log.e("characteristic 的 uuid:", "${characteristic.uuid}")
                        characteristic.descriptors.forEach { descrip ->
                            Log.e("descrip 的 uuid:", "${descrip.uuid}")
                        }
                    }
                }
            }
             */
        }

        // 读数据回调
        override fun onCharacteristicRead(
            gatt: BluetoothGatt?,
            characteristic: BluetoothGattCharacteristic?,
            status: Int
        ) {
            super.onCharacteristicRead(gatt, characteristic, status)
            characteristic?.let {
                val byteArray : ByteArray = it.value
//                Bus.send(DeviceInfoReadEvent(byteArray))
//                val data = String(it.value)
//                logInfo("CharacteristicRead 数据: $data")
            }
        }

        // 写数据回调 *****
        override fun onCharacteristicWrite(
            gatt: BluetoothGatt?,
            characteristic: BluetoothGattCharacteristic?,
            status: Int
        ) {
            super.onCharacteristicWrite(gatt, characteristic, status)
            characteristic?.let {
                val data = String(it.value)
//                logInfo("CharacteristicWrite 数据: $data")
                runOnUiThread {
                    if (floatMenuPosition == 6) {
                        deviceNameTv!!.text = data
                    }
                    val toast = Toast.makeText(this@DeviceListActivity, "OK", Toast.LENGTH_SHORT)
                    toast.setGravity(Gravity.CENTER, 0, 0)
                    toast.show()
                }

            }
        }

        //通知数据
        override fun onCharacteristicChanged(
            gatt: BluetoothGatt?,
            characteristic: BluetoothGattCharacteristic?
        ) {
            super.onCharacteristicChanged(gatt, characteristic)
            if (null != mReceiverRequestQueue) {
//                val map = mReceiverRequestQueue.map
                val rec = characteristic!!.getValue()
//                for (key in mReceiverRequestQueue.map.keys) {
//                    val onReceiverCallback = map[key]
//                    runOnMainThread(Runnable { onReceiverCallback!!.onReceiver(rec) })
//                }

                // 电量
                var currentPower : Int = 0
                currentPower = convertTwoInt(rec, 6,5)
                if (lastPower != currentPower) {
                    lastPower = currentPower
                    power = currentPower
                    mData[connectedPosition].power = power
                    // UI线程更新电量
                    runOnUiThread {
                        mBleAdapter.notifyItemChanged(connectedPosition)
                    }
                }

                // 报警
                var warnStatus : Int =  rec[33].toInt() and 0xFF
                if (warnStatus != 0) {
                    // MS5611温度
                    var temperature : Int = 0
                    temperature = convertTwoInt(rec, 8,7)
                    // MS5611海拔高度
                    var altitude  = 0
                    altitude = convertTwoInt(rec, 10,9)
                    Bus.send(DeviceMessagePublishEvent(warnStatus,temperature,altitude))
                }
//              Bus.send(DeviceInfoReadEvent(rec))
            }

//            characteristic?.let {
//                val data = String(it.value)
////              logInfo("CharacteristicChanged 数据: $data")
//            }
        }

        override fun onDescriptorRead(
            gatt: BluetoothGatt?,
            descriptor: BluetoothGattDescriptor?,
            status: Int
        ) {
            super.onDescriptorRead(gatt, descriptor, status)
            descriptor?.let {
                val data = String(it.value)
//              logInfo("DescriptorRead 数据: $data")
            }
        }

        override fun onDescriptorWrite(
            gatt: BluetoothGatt?,
            descriptor: BluetoothGattDescriptor?,
            status: Int
        ) {
            super.onDescriptorWrite(gatt, descriptor, status)
            descriptor?.let {
//              val data = String(it.value)
//              logInfo("DescriptorWrite 数据: $data")
            }
        }

    }

    private fun runOnMainThread(runnable: Runnable) {
        if (isMainThread()) {
            runnable.run()
        } else {
            if (mHandler != null) {
                mHandler.post(runnable)
            }
        }
    }
    private fun isMainThread(): Boolean {
        return Looper.myLooper() == Looper.getMainLooper()
    }

    /**
     * 读数据
     */
    fun readData(view: View) {
        //找到 gatt 服务
        val service = getGattService(BleBlueImpl.UUID_SERVICE)
        if (service != null) {
            val characteristic =
                service.getCharacteristic(BleBlueImpl.UUID_READ_NOTIFY) //通过UUID获取可读的Characteristic
            mBluetoothGatt?.readCharacteristic(characteristic)
        }
    }

    // 获取Gatt服务
    private fun getGattService(uuid: UUID): BluetoothGattService? {
        if (!isConnected) {
            Toast.makeText(this, "没有连接", Toast.LENGTH_SHORT).show()
            return null
        }
        val service = mBluetoothGatt?.getService(uuid)
        if (service == null) {
            Toast.makeText(this, "没有找到服务", Toast.LENGTH_SHORT).show()
        }
        return service
    }

    fun writeData(view: View) {
//        val msg = editText.text.toString()
//        val service = getGattService(BleBlueImpl.UUID_SERVICE)
//        if (service != null) {
//            val characteristic =
//                service.getCharacteristic(BleBlueImpl.UUID_WRITE) //通过UUID获取可读的Characteristic
//            characteristic.value = msg.toByteArray()
//            mBluetoothGatt?.writeCharacteristic(characteristic)
//        }
    }

    // 2字节
    fun convertTwoInt(byteArray: ByteArray, indexH : Int, indexL: Int): Int {
        if (byteArray[indexH] < 0 || byteArray[indexL] < 0) {
            return (byteArray[indexH].toInt() shl 8) or (byteArray[indexL].toInt() and 0xFF)
        } else {
            return (byteArray[indexH].toInt() and 0xFF) shl 8 or (byteArray[indexL].toInt() and 0xFF)
        }
    }

    // 4字节
    fun convertFourInt(byteArray: ByteArray, index1 : Int, index2: Int,index3 : Int, index4: Int): Int {
        if (byteArray[index1] < 0 || byteArray[index1] < 0|| byteArray[index3] < 0 || byteArray[index4] < 0) {
            return (byteArray[index4].toInt() shl 24) or (byteArray[index3].toInt() and 0xFF) or (byteArray[index2].toInt() shl 8) or (byteArray[index1].toInt() and 0xFF)
        } else {
            return (byteArray[index4].toInt() and 0xFF)  shl 24 or (byteArray[index3].toInt() and 0xFF) shl 16 or (byteArray[index2].toInt() and 0xFF) shl 8 or (byteArray[index1].toInt() and 0xFF)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
//        closeConnect()
    }

    // 定时器
    class MessageTimerTask(val uuid: UUID, val mBluetoothGatt: BluetoothGatt) : TimerTask() {
        val service = mBluetoothGatt?.getService(uuid)
        override fun run() {
            val characteristic =
                service.getCharacteristic(BleBlueImpl.UUID_READ_NOTIFY) //通过UUID获取可读的Characteristic
                mBluetoothGatt?.readCharacteristic(characteristic)
        }
    }

    /**
     * 设置通知
     *
     * @param enable         true为开启false为关闭
     * @param characteristic 通知特征
     * @return
     */
    private fun enableNotification(
        enable: Boolean,
        characteristic: BluetoothGattCharacteristic?
    ): Boolean {
        if (blueGatt == null || characteristic == null)
            return false
        if (!blueGatt!!.setCharacteristicNotification(characteristic, enable))
            return false
        val clientConfig = characteristic.getDescriptor(UUID.fromString(BleBlueImpl.BLUETOOTH_NOTIFY_D))
            ?: return false

        if (enable) {
            clientConfig.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
        } else {
            clientConfig.value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
        }
        return blueGatt!!.writeDescriptor(clientConfig)
    }

    fun getService(uuid: UUID): BluetoothGattService? {
        if (mBleAdapter == null || blueGatt == null) {
            Log.e(TAG, "BluetoothAdapter not initialized")
            return null
        }
        return blueGatt!!.getService(uuid)
    }

    /**
     * 根据服务UUID和特征UUID,获取一个特征[BluetoothGattCharacteristic]
     *
     * @param serviceUUID   服务UUID
     * @param characterUUID 特征UUID
     */
    private fun getBluetoothGattCharacteristic(
        serviceUUID: String,
        characterUUID: String
    ): BluetoothGattCharacteristic? {
        require(isEnable()) { " Bluetooth is no enable please call BluetoothAdapter.enable()" }
        if (null == blueGatt) {
            Log.e(TAG, "mBluetoothGatt is null")
            return null
        }

        //找服务
        val bluetoothGattCharacteristicMap = servicesMap[serviceUUID]
        if (null == bluetoothGattCharacteristicMap) {
            Log.e(TAG, "Not found the serviceUUID!")
            return null
        }

        //找特征
        val entries = bluetoothGattCharacteristicMap.entries
        var gattCharacteristic: BluetoothGattCharacteristic? = null
        for ((key, value) in entries) {
            if (characterUUID == key) {
                gattCharacteristic = value
                break
            }
        }
        return gattCharacteristic
    }

    /**
     * 当前蓝牙是否打开
     */
    private fun isEnable(): Boolean {
        return if (null != bluetoothAdapter) {
            bluetoothAdapter!!.isEnabled
        } else false
    }

    // TODO 此方法断开连接或连接失败时会被调用。可在此处理自动重连,内部代码可自行修改，如发送广播
    private fun reConnect() {
        if (connectCallback != null) {
            runOnMainThread(Runnable { connectCallback!!.onConnFailed() })
        }

        Log.e(TAG, "Ble disconnect or connect failed!")
    }

    // TODO 此方法Notify成功时会被调用。可在通知界面连接成功,内部代码可自行修改，如发送广播
    private fun connSuccess() {
        if (connectCallback != null) {
            runOnMainThread(Runnable { connectCallback!!.onConnSuccess() })
        }
        Log.e(TAG, "Ble connect success!")
    }


}